import emojiList from '@/common/emojiList.js';

export default {
	data() {
		return {
			yuming: 'https://ndj.techqianmo.com',
			// 'https://neidangjia.oss-cn-beijing.aliyuncs.com'
			oss: 'https://neidangjia.oss-accelerate.aliyuncs.com',
			rongyun: 'https://api-cn.ronghub.com',
			pnum: 10,
			city: '',
			keyword: '',
			highly: 0,
			elementTop: 0,
			highlyTop: 0,
			pagescrollTop: 0,
			dataList: [],
			path: '',
			emojiList, // 表情
			params: {
				p: 1
			},
			listStatus: 'nomore',
			colorList: ['#00B7EE', '#9BD338', '#D37A38', '#30A238', '#A28130', '#5FDEE3', '#A25330'],
			obtain: false,
			userId: null,
			company: '内当家', // 公司小程序名称
			logo: 'https://neidangjia.oss-accelerate.aliyuncs.com/df/logo.png',
			pageLoad: true,
			df: 'https://neidangjia.oss-accelerate.aliyuncs.com/df/df.png',
			requestStatus: true,
			cityall: [],
			sys: {
				top: 0,
				height: 0,
				bottom: 0
			}
		}
	},
	onReady() {
		this.sumHeigly('.heighly');
		// this.sumHeigly('.elementTop', 'top');
	},
	async onPullDownRefresh() {
		// 下拉刷新
		this.params.p = 1;
		await this.getList();
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 1000);
	},
	onPageScroll(e) {
		this.pagescrollTop = e.scrollTop;
	},
	async onTabItemTap(e) {
		if (e.index === 2 || e.index === 3 || e.index === 4) {
			let login = await this.getMobile();
			if (!login) {
				return;
			}
		}
	},
	onReachBottom() {
		// 上拉加载
		this.reachBottom();
	},
	onLoad() {
		let sys = uni.$u.sys();
		this.sys = {
			top: sys.safeArea.top,
			height: sys.safeArea.height,
			bottom: sys.screenHeight - sys.safeArea.bottom
		};
	},
	methods: {
		toMap(latitude, longitude) {
			uni.openLocation({
				latitude: +latitude,
				longitude: +longitude,
				success: () => {}
			});
		},
		get_look_two($num) {
			if (!$num || !/^\d+$/.test($num)) {
				return 0
			}
			if ($num >= 1000 && $num < 10000) {
				return ($num / 1000).toFixed(1) + '千'
			} else if ($num >= 10000) {
				return ($num / 10000).toFixed(1) + '万'
			} else {
				return $num;
			}
		},
		randomString() {
			let len = 18;
			var $chars =
				'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
			var maxPos = $chars.length;
			var pwd = '';
			for (var i = 0; i < len; i++) {
				pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
			}
			return pwd;
		},
		getSign(params, kAppKey, kAppSecret) {
			if (typeof params == "string") {
				return paramsStrSort(params);
			} else if (typeof params == "object") {
				var arr = [];
				for (var i in params) {
					arr.push((i + "=" + params[i]));
				}
				return paramsStrSort(arr.join(("&")));
			}
		},
		paramsStrSort(paramsStr) {
			var url = paramsStr + "&appKey=" + kAppKey;
			var urlStr = url.split("&").sort().join("&");
			var newUrl = urlStr + '&key=' + kAppSecret;
			return md5(newUrl);
		},
		// 是否小程序
		isMini() {
			// #ifdef MP-WEIXIN
			return true;
			// #endif
			return false;
		},
		// 是否移动端
		isMobile() {
			// #ifdef H5
			var browser = {
				versions: function() {
					var u = navigator.userAgent,
						app = navigator.appVersion;
					return { // 移动终端浏览器版本信息  
						trident: u.indexOf('Trident') > -1, // IE内核 
						presto: u.indexOf('Presto') > -1, // opera内核 
						webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核 
						gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, // 火狐内核 
						mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端 
						ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端 
						android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -
							1, // android终端或者uc浏览器 
						iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器 
						iPad: u.indexOf('iPad') > -1, // 是否iPad   
						webApp: u.indexOf('Safari') == -1 // 是否web应该程序，没有头部与底部 
					};
				}(),
				language: (navigator.browserLanguage || navigator.language).toLowerCase()
			}
			//如果是移动端就进行这里
			if (browser.versions.mobile || browser.versions.ios || browser.versions.android ||
				browser.versions.iPhone || browser.versions.iPad) {
				return true
			} else {
				//pc端进入这里
				return false
			}
			// #endif
			return false
		},
		// 是否H5的微信浏览器
		isWeiXinBrowser() {
			// #ifdef H5
			let ua = window.navigator.userAgent.toLowerCase()
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				return true
			}
			// #endif
			return false
		},
		// 是否微信小程序或者微信浏览器
		isWx() {
			// #ifdef MP-WEIXIN
			return true;
			// #endif
			// #ifdef H5
			if (this.isMobile()) {
				if (this.isWeiXinBrowser()) {
					return true;
				}
			}
			// #endif
			return false;
		},
		shareApp(path) {
			// #ifdef APP-PLUS
			uni.share({
				provider: "weixin",
				scene: "WXSenceTimeline",
				href: path + '?share=share&agentid=' + this.userId,
				success: function(res) {},
				fail: function(err) {}
			});
			// #endif
		},
		// 转换时间
		get_time(time) {
			let timestamp = 0;
			if (time.indexOf("-") != -1) {
				time = time.replace(/-/g, '/')
				timestamp = +(Date.parse(time) / 1000)
			} else {
				timestamp = +(time / 1000)
			}

			function zeroize(num) {
				return (String(num).length == 1 ? '0' : '') + num;
			}
			var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
			var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
			var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
			var tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象
			var Y = tmDate.getFullYear(),
				m = tmDate.getMonth() + 1,
				d = tmDate.getDate();
			var H = tmDate.getHours(),
				i = tmDate.getMinutes(),
				s = tmDate.getSeconds();
			if (timestampDiff < 60) { // 一分钟以内
				return "刚刚";
			} else if (timestampDiff < 3600) { // 一小时前之内
				return Math.floor(timestampDiff / 60) + "分钟前";
			} else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
				return '今天' + zeroize(H) + ':' + zeroize(i);
			} else {
				var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
				if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
					return '昨天' + zeroize(H) + ':' + zeroize(i);
				} else if (curDate.getFullYear() == Y) {
					return zeroize(m) + '/' + zeroize(d) + ' ' + zeroize(H) + ':' + zeroize(i);
				} else {
					return Y + '/' + zeroize(m) + '/' + zeroize(d) + ' ' + zeroize(H) + ':' + zeroize(i);
				}
			}
		},
		// 验证用户角色  async
		// if (!await this.getMobile()) {
		// 	return;
		// }
		getMobile(sub) {
			return new Promise(async (resolve, reject) => {
				let login = false;
				try {
					const mobile = uni.getStorageSync('mobile');
					if (mobile) {
						login = true;
					} else {
						let dataAdd = await this.wxminLogin();
						if (dataAdd) {
							if (dataAdd.obtain) {
								if (sub === 'sub') {
									this.$emit('newObj', dataAdd);
								} else {
									this.obtain = dataAdd.obtain;
									this.userId = dataAdd.userId;
								}
								login = false;
							} else {
								if (sub === 'sub') {
									this.$emit('getNew');
								} else {
									await this.getNew();
								}
								login = true;
							}
						} else {
							login = false;
						}
					}
					resolve(login);
				} catch (e) {
					console.log(e);
				}
			})
		},
		// 组件传值到data
		newObj(obj) {
			for (let var1 in obj) {
				this[var1] = obj[var1];
			}
		},
		xinxiao() {
			let that = this;
			let interval = setInterval(() => {
				if (uni.getStorageSync('senderUserId')) {
					that.$ry.Conversation.getTotalUnreadCount(false, [1]).then(count => {
						console.log('获取未读总数成功', count);
						uni.setStorageSync('xinxiaoxi', count);
						if (count > 0) {
							uni.showTabBarRedDot({
								index: 3
							});
						} else {
							uni.hideTabBarRedDot({
								index: 3
							});
						}
					});
					clearInterval(interval);
				}
			}, 1000);
		},
		async wxminLogin() {
			let dataAdd = {};
			let dataRes = await this.mobile();
			if (dataRes) {
				dataAdd = dataRes
			}
			// #ifdef MP-WEIXIN
			try {
				const mobile = uni.getStorageSync('mobile');
				if (!mobile) {
					dataAdd.obtain = true
				}
			} catch (e) {}
			// #endif
			return dataAdd
		},
		// 校验mobile
		async mobile() {
			try {
				const mobile = uni.getStorageSync('mobile');
				const userId = uni.getStorageSync('userId');
				if (!userId) {
					// #ifdef MP-WEIXIN
					let dataAdd = await this.getinfo();
					if (dataAdd) {
						return dataAdd;
					}
					// #endif

					// #ifdef MP-TOUTIAO
					let dataToutiao = await this.getinfoBytoutiao();
					if (dataToutiao) {
						return dataToutiao;
					}
					// #endif
					
					// #ifdef H5
					if (vm.isWxBrowser()) {
						location.href = '';
						return {}
					} else {
						this.nextNav('/pages/login/login');
						return {}
					}
					// #endif

					// #ifdef APP-PLUS
					this.nextNav('/pages/login/login');
					return {}
					// #endif
				} else {
					let url = this.$u.mpShare.path;
					if (url.indexOf('agentid') == -1) {
						url += (url.indexOf('?') == -1 ? '?' : '&') + 'agentid=' + dataNew.data.id;
						this.$u.mpShare.path = url;
					}
					if (!mobile) {
						return {
							userId,
							obtain: true
						}
					} else {
						return {
							obtain: false
						}
					}
				}
			} catch (e) {}
		},
		getinfoBytoutiao() {
			let that = this;
			return new Promise(async (resolve, reject) => {
				let dataAdd = {};
				uni.login({
					provider: 'toutiao',//这里服务商名是字节跳动小程序 所以填toutiao
					success: function (loginRes) {
						console.log(loginRes);//获取到当前用户的code
						// uni.request({//请求获取openid
						// 	url: 'https://developer.toutiao.com/api/apps/jscode2session', 
						// 	data: {
						// 		code: loginRes.code,//上面获取到的用户的code
						// 		appid:'',//小程序的AppID
						// 		secret:''//小程序的AppSecret
						// 	},
						// 	success: (res) => {
						// 		console.log(resres.data.openid);
						// 	}
						// });
					}
				});
			})
		},
		getinfo() {
			let that = this;
			return new Promise(async (resolve, reject) => {
				let dataAdd = {};
				uni.getUserProfile({
					desc: '登录',
					success: (res) => {
						uni.login({
							success: async (result) => {
								let params = {
									code: result.code,
									nickName: res.userInfo.nickName,
									avatarUrl: res.userInfo.avatarUrl,
									gender: res.userInfo.gender,
									pid: uni.getStorageSync('agentid') || ''
								}
								let dataNew = await this.require('wxminLogin',
									params);
								if (dataNew && dataNew.token) {
									uni.setStorageSync('token', dataNew.token);
									this.$u.http.setConfig((config) => {
										config.header = {
											token: dataNew.token
										}
										return config
									})
									let userInfo = await this.require('userInfo');
									if (userInfo) {
										let url = this.$u.mpShare.path;
										if (url.indexOf('agentid') == -1) {
											url += (url.indexOf('?') == -1 ? '?' :
												'&') + 'agentid=' + userInfo.id;
											this.$u.mpShare.path = url;
										}
										dataAdd.userId = userInfo.id;
										dataAdd.userInfo = userInfo;
										uni.setStorageSync('userId', userInfo.id);
										uni.setStorageSync('userInfo', JSON
											.stringify(userInfo));
										if (userInfo.mobile) {
											uni.setStorageSync('mobile', userInfo
												.mobile);
											uni.setStorageSync('rong_token',
												userInfo.rong_token);
											if (uni.getStorageSync('rong_token')) {
												this.$ry.connect({
													token: uni
														.getStorageSync(
															'rong_token')
												}).then(async user => {
													console.log(
														'链接成功, 链接用户 id 为: ',
														user.id);
													uni.setStorageSync(
														'senderUserId',
														user.id);
													this.xinxiao();
													await that.require(
														'postrongyunid', {
															senderUserId: user
																.id
														})
													uni.setStorageSync(
														'userInfo',
														JSON
														.stringify({
															...
															userInfo,
															senderUserId: user
																.id
														}));
												}).catch(error => {
													console.log('链接失败: ',
														error.code,
														error.msg);
												});
											}
											dataAdd.obtain = false;
										} else {
											dataAdd.obtain = true;
										}
									}
									uni.showToast({
										title: userInfo.msg,
										duration: 1200,
										icon: 'none'
									});
									resolve(dataAdd);
								}
							}
						});
					}
				});
			})
		},
		/**
		 * 下载单个文件
		 * @param {string} [type]
		 * @param {string} url
		 * @callback successCallback
		 * @callback failCallback
		 */
		downloadFile(type, url, successc, failc) {
			this.checkAuth(() => {
				this.downloadSaveFile(
					type,
					url,
					() => {
						uni.showToast({
							title: '下载成功',
							icon: 'none',
						})
						successc && successc();
					},
					(errMsg) => {
						uni.showToast({
							title: errMsg,
							icon: 'none',
						})
						failc && failc();
					}
				);
			})
		},
		checkAuth(gotc) {
			//查询权限
			// #ifdef MP-WEIXIN
			uni.getSetting({
				success(res) {
					if (!res.authSetting['scope.writePhotosAlbum']) {
						//请求授权
						uni.authorize({
							scope: 'scope.writePhotosAlbum',
							success() {
								//获得授权，开始下载
								gotc && gotc();
							},
							fail() {
								uni.showModal({
									title: '',
									content: '保存到系统相册需要授权',
									confirmText: '授权',
									success(res) {
										if (res.confirm) {
											uni.openSetting({
												success(res) {
													if (res.authSetting[
															'scope.writePhotosAlbum'
														] === true) {
														gotc && gotc();

													}
												}
											})
										}
									},
									fail() {
										uni.showToast({
											title: '打开设置页失败',
											icon: 'none',
										})

									}
								})
							}
						})
					} else {
						//已有授权
						gotc && gotc();
					}
				},
				fail() {
					uni.showToast({
						title: '获取授权失败',
						icon: 'none',
					})
				}
			})
			// #endif
			// #ifndef MP-WEIXIN
			gotc && gotc();
			// #endif
		},
		//下载文件
		downloadSaveFile(type, url, successc, failc) {
			// #ifndef H5
			uni.downloadFile({
				url: url,
				success: res => {
					if (res.statusCode === 200) {
						if (type === 'video') {
							//类型为视频
							uni.saveVideoToPhotosAlbum({
								filePath: res.tempFilePath,
								success: res => {
									successc && successc();
								},
								fail: res => {
									failc && failc('保存失败');
								}
							})
						} else if (type === 'image') {
							//类型为图片
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: res => {
									successc && successc();
								},
								fail: res => {
									failc && failc('保存失败');
								}
							})
						}
					} else {
						failc && failc('状态码非200');
					}
				}
			})
			// #endif

			// #ifdef H5
			window.open(url + '?response-content-type=application/octet-stream');
			successc && successc();
			// #endif
		},
		// 随机颜色
		randomColor(index, idx) {
			let index_idx = index + '_' + idx;
			const indexOld = uni.getStorageSync('index_idx');
			if (indexOld) {
				if (index_idx === indexOld) {
					return uni.getStorageSync('colorOld');
				} else {
					let colorNew = this.colorRandom();
					while (colorNew === uni.getStorageSync('colorOld')) {
						colorNew = this.colorRandom();
					}
					uni.setStorageSync('index_idx', index_idx);
					uni.setStorageSync('colorOld', colorNew);
					return colorNew
				}
			} else {
				uni.setStorageSync('index_idx', index_idx);
				let num = uni.$u.random(0, this.colorList.length - 1);
				uni.setStorageSync('colorOld', this.colorList[num]);
				return this.colorList[num]
			}
		},
		// 不同颜色值
		colorRandom() {
			let num = uni.$u.random(0, this.colorList.length - 1);
			return this.colorList[num]
		},
		// 获取列表
		async getList(add) {
			let res = await this.require(this.path, this.params);
			if (res) {
				if (add === 'add') {
					this.dataList = this.dataList.concat(res);
				} else {
					this.dataList = res;
				}
				this.listStatus = res.length === this.pnum ? 'loadmore' : 'nomore';
			} else {
				this.listStatus = 'nomore';
			}
		},
		// 上拉加载
		reachBottom() {
			if (this.listStatus === 'nomore') {
				return;
			}
			this.params.p++;
			this.listStatus = 'loading';
			this.getList('add');
		},
		// 计算高度
		sumHeigly(element, top) {
			let _this = this;
			let win_height = 0;
			uni.getSystemInfo({
				success(res) {
					win_height = res.windowHeight;
				}
			});
			const query = uni.createSelectorQuery()
			query.select(element).boundingClientRect()
			query.selectViewport().scrollOffset()
			query.exec(function(res) {
				if (res[0]) {
					if (top) {
						_this.elementTop = res[0].top;
						console.log(_this.elementTop, 'elementTop');
					} else {
						_this.highlyTop = res[0].top;
						_this.highly = win_height - res[0].top;
						// console.log(_this.highly, 'highly');
					}
				}
			})
		},
		// 自定义请求
		async require(path, data) {
			let res = await this.$api[path](data);
			if (res) {
				return res;
			}
		},
		selectPhoneNumber(str) {
			var regx = /(1[3|4|5|7|8][\d]{9}|0[\d]{2,3}-[\d]{7,8}|400[-]?[\d]{3}[-]?[\d]{4})/g;
			var phoneNums = str.match(regx);
			if (phoneNums) {
				for (var i = 0; i < phoneNums.length; i++) {
					var temp = phoneNums[i]
					str = str.replace(phoneNums[i], '<a href="' + temp +
						'" style="color:#56cef0;text-decoration:none;"> ' + temp + ' </a>');
				}
			}
			return str;
		},
		selectVideo(str) {
			var regx = /^http?.+\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4)$/g;
			var video = str.match(regx);
			if (video) {
				for (var i = 0; i < video.length; i++) {
					var temp = video[i]
					str = str.replace(temp, '<a href="' + temp +
						'" style="color:#56cef0;text-decoration:none;"> ' + temp + ' </a>');
				}
			}
			return str;
		},
		// 减法
		accSub(arg1, arg2) {
			var r1, r2, m, n;
			try {
				r1 = arg1.toString().split(".")[1].length;
			} catch (e) {
				r1 = 0;
			}
			try {
				r2 = arg2.toString().split(".")[1].length;
			} catch (e) {
				r2 = 0;
			}
			m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
			n = (r1 >= r2) ? r1 : r2;
			return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
		},
		// 跳转页面
		async nextNav(URL, key) {
			if (key == 1) {
				if (!await this.getMobile()) {
					return;
				}
			}
			switch (URL) {
				case 'no':
					uni.showModal({
						title: '功能暂未开放！'
					})
					break;
				case 'back':
					uni.navigateBack();
					break;
				case 'back2':
					uni.navigateBack({
						delta: 2
					})
					break;
				case '/pages/tabbar/index':
					uni.switchTab({
						url: URL
					})
					break;
				case '/pages/tabbar/news':
					uni.switchTab({
						url: URL
					})
					break;
				case '/pages/tabbar/recommend':
					uni.switchTab({
						url: URL
					})
					break;
				case '/pages/tabbar/consult':
					uni.switchTab({
						url: URL
					})
					break;
				case '/pages/tabbar/mine':
					uni.switchTab({
						url: URL
					})
					break;
				default:
					uni.navigateTo({
						url: URL
					})
					break;
			}
		}
	}
}
